<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import { Button, Popconfirm } from 'ant-design-vue';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { farmDeleteApi, getFarmLabelListApi, getFarmListApi } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import UserOperateDrawer from './modules/operate-drawer.vue';
import TypeDrawer from './modules/type-drawer.vue';
import UserSearch from './modules/search.vue';

const projectStore = useProjectStore();

const { tableWrapperRef, scrollConfig } = useTableScroll();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: getFarmListApi,
  apiParams: {
    pageNo: 1,
    pageSize: 10,
    projectId: projectStore.currentProject?.id
  },
  columns: (): any => [
    {
      key: 'sequence',
      dataIndex: 'sequence',
      title: '序号',
      width: 60
    },
    {
      key: 'name',
      dataIndex: 'name',
      title: '养殖池名称'
    },
    {
      key: 'sort',
      dataIndex: 'sort',
      title: '养殖品种'
    },
    {
      key: 'labelId',
      dataIndex: 'labelId',
      title: '分类',
      customRender: ({ record }: any) => {
        return farmLabelList.value.find((item: any) => item.id === record.labelId)?.label;
      }
    },
    {
      key: 'remark',
      dataIndex: 'remark',
      title: '备注'
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      width: 160,
      sorter: true
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      width: 160
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 140,
      customRender: ({ record }: any) => (
        <div class="flex-center gap-8px">
          <Button type="primary" ghost size="small" onClick={() => edit(record.id)}>
            编辑
          </Button>
          <Popconfirm title="确认删除吗？" onConfirm={() => handleDelete(record.id)}>
            <Button danger size="small">
              删除
            </Button>
          </Popconfirm>
        </div>
      )
    }
  ]
});

const sortChange = (pagination, filters, sorter) => {
  console.log('sorter', sorter);
};

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onDeleted } = useTableOperate(
  data as any,
  getData
);

async function handleDelete(id: any) {
  const res = await farmDeleteApi(id);
  if (res.error === null) await onDeleted();
}

function edit(id: number) {
  handleEdit(id);
}

/* 分类弹出框逻辑 */
const typeDrawerVisible = ref(false);
/* 分类弹出框逻辑 */

/* 获取分类列表 */
const farmLabelList = ref([]);
const getLabelList = () => {
  getFarmLabelListApi({
    projectId: projectStore.currentProject?.id
  }).then(res => {
    if (res.data) {
      farmLabelList.value = res.data.data;
    }
  });
};

onMounted(() => {
  getLabelList();
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch
      v-model:farmLabelList="farmLabelList"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <ACard
      title="养殖池列表"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getData"
        >
          <template #suffix>
            <AButton size="small" @click="typeDrawerVisible = true">分类管理</AButton>
          </template>
        </TableHeaderOperation>
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :scroll="scrollConfig"
        :loading="loading"
        row-key="id"
        :pagination="mobilePagination"
        class="h-full"
        children-column-name="childDeviceInfo"
        @change="sortChange"
      />

      <UserOperateDrawer
        v-model:visible="drawerVisible"
        v-model:farmLabelList="farmLabelList"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
      <TypeDrawer v-model:visible="typeDrawerVisible" />
    </ACard>
  </div>
</template>

<style scoped></style>
